import random
import sounddevice as sd
import numpy as np
import scipy.io.wavfile as wav

def get_user_choice():
    while True:
        print("请击打桌面，测试您的力度（1-10）：")
        intensity, audio_data = record_sound()
        if intensity >= 1 and intensity <= 10:
            print("力度:", intensity)
            return map_intensity_to_choice(intensity), audio_data
        else:
            print("力度无效，请重新测试！")

def map_intensity_to_choice(intensity):
    if intensity <= 4:
        return "剪刀"
    elif intensity <= 7:
        return "石头"
    else:
        return "布"

def get_computer_choice():
    choices = ['剪刀', '石头', '布']
    return random.choice(choices)

def determine_winner(user_choice, computer_choice):
    if user_choice == computer_choice:
        return "平局"
    elif (user_choice == '剪刀' and computer_choice == '布') or \
        (user_choice == '石头' and computer_choice == '剪刀') or \
        (user_choice == '布' and computer_choice == '石头'):
        return "用户胜利"
    else:
        return "电脑胜利"

def record_sound():
    duration = 1.0  # 录制音频的时间长度（单位：秒）
    fs = 44100  # 采样率
    recording = sd.rec(int(duration * fs), samplerate=fs, channels=1)

    print("请击打桌面...")
    sd.wait()  # 等待录制完成
    
    # 分析音频数据的振幅
    amplitude = np.abs(recording).mean()

    # 将振幅映射到1-10的数字范围
    intensity = round(10 * (amplitude / np.max(amplitude)))

    # 保存录制的音频到文件
    filename = "recording.wav"
    wav.write(filename, fs, recording)

    return intensity, filename

def play_game():
    print("欢迎来到剪刀石头布游戏！")
    while True:
        user_choice, user_audio = get_user_choice()
        computer_choice = get_computer_choice()
        print("用户选择:", user_choice)
        print("电脑选择:", computer_choice)
        winner = determine_winner(user_choice, computer_choice)
        print("结果:", winner)
        play_again = input("是否再玩一局？(是/否)：")
        if play_again == '否':
            break

play_game()
